/*
TP Peripherique
Copyright 2009 Boris Maquin, Paul Cox 

File: swuart.c
Version: 2
*/

#include <intrins.h>	// pour la fonction void _nop_(void)
#include <reg167.h>		// pour P2, DP2, ODP2  
#include "swuart.h"

// P2.11
void init_swuart() {
	ODP2 = ODP2 & ~(0x0800);
	DP2 = DP2 | 0x0800;
	init_adc();
}

void Attendons (long int Duree)	{

	long Compte;

	Compte = Duree ;
	while (Compte > 0 ){
		_nop_();
		Compte = Compte-1;
	}
}

//Data is output on P2.11 at 9600 baud (bit time of 104 us)
//char is preceded by a start bit (low), sent one bit at a time,
//and followed by one period of high (stop bit).

void put_char1(char char1){
	 int i;

	 //send start bit
	 //P2 = P2 & ~(0x0800);
	 P2 = P2 & ~(0x0800);
	 Attendons(130);
	 //send char
 	 for (i=0; i<8; i++){
	 	if ( char1 & 0x0001 ){
			//raise GPIO high for one bit interval
			P2 = P2 | 0x0800;
			Attendons(130);
	 	} else {
			//lower GPIO for one bit interval
			P2 = P2 & ~(0x0800);
			Attendons(130);	
	   	}
		char1 = char1>>1;
	}
	//send stop bit
	P2 = P2 | 0x0800;
	Attendons(338);
}	

void init_adc(){
	P5DIDIS = 0x0002;
	ADCON = 0x0001;
}			

int read_bat_level() {
    // Checks battery level and if below x V ()
	//returns 1 meaning bat level LOW
	// 0 means all is well
	
	ADCON |= 0x0080; //start conversion
	while ( ADCON & 0x0100 ) { //wait for busy flag to clear
	 _nop_();
	}

	if ( ADDAT < 0x0333 ) { //1024 * 0.8 = 819 (0x333)
		return 1;
	} else {
		return 1;
	}
}